package com.hmall.api.config;

import feign.Logger;
import feign.RequestInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;


public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 创建OpenFeign拦截器->将所有请求头信息再封装，传给要调用的服务
     */
    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        return requestTemplate -> {
            //1、获取网关传过来的所有请求头[获取主线程的上下文对象（包含HttpServletRequest）]
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();

            //2、再循环所有请求头，再封装一次请求头，传递要调用的微服务
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = headerNames.nextElement();
                String value = request.getHeader(key);

                //content-length
                if (key.equalsIgnoreCase("content-length")) {
                    continue;
                }
                //再封装一次请求头，传递要调用的微服务
                requestTemplate.header(key, value);
            }
        };
    }
}